#pragma once

#include <string>
#include <vector>

using namespace std;

class Buffer {
public:
    static const size_t kInitialSize = 1024;
    explicit Buffer(size_t initialSize = kInitialSize)
        : buffer_(initialSize),
        readIndex(0),
        writeIndex(0) 
    {
        // buffer_.reserve(kInitialSize);
    }

    ssize_t readFd(int fd, int* savedErrno);
    
    void append(const std::string& str) { append(str.data(), str.size()); }
    void append(const char* data, size_t len);
    // void append(const void* data, size_t len);

    size_t readableBytes() const { return writeIndex - readIndex; }
    size_t writableBytes() const { return buffer_.size() - writeIndex; }
    const char* peek() const { return begin() + readIndex; }
    const char* findCRLF() const;
    const char* find12() const;

    // 移动readIndex
    void retrieveAll() { readIndex = 0; writeIndex = 0; }
    void retrieve(size_t len);
    void retrieveUntil(const char* end) { retrieve(end - peek()); }

    string retrieveAllAsString() { return retrieveAsString(readableBytes()); }
    string retrieveAsString(size_t len) {
        // assert(len <= readableBytes());
        string result(peek(), len);
        retrieve(len);
        return result;
    }
    string retrieveAsUntilString(const char* end) {
        // assert(len <= readableBytes());
        size_t len = end - peek();
        string result(peek(), len);
        retrieve(len);
        return result;
    }

    char* begin() { return &*buffer_.begin(); }
    const char* begin() const { return &*buffer_.begin(); }

    char* beginWrite() { return begin() + writeIndex; }
    const char* beginWrite() const { return begin() + writeIndex; }
    
    size_t prependableBytes() const { return readIndex; }

    void ensureWritableBytes(size_t len)
    {
        if (writableBytes() < len)
        {
            makeSpace(len);
        }
        // assert(writableBytes() >= len);
    }

    void makeSpace(size_t len)
    {
        if (writableBytes() + prependableBytes() < len)
        {
            // FIXME: move readable data
            buffer_.resize(writeIndex+len);
        }
        else
        {
            size_t readable = readableBytes();
            std::copy(begin()+readIndex, begin()+writeIndex, begin());
            readIndex = 0;
            writeIndex = readIndex + readable;
        }
    }

    void hasWritten(size_t len)
    {
        // assert(len <= writableBytes());
        writeIndex += len;
    }

    bool readable() const { return readableBytes() > 0; }

private:
    std::vector<char> buffer_;
    size_t readIndex;
    size_t writeIndex;
    static const char kCRLF[];
    static const char kOneTwo[];
};